package com.cw.jeeyt.controller.api;

import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cw.jeeyt.api.dto.response.JsonResultDto;
import com.cw.jeeyt.common.DataTable;
import com.cw.jeeyt.common.DownLoadTemplateUtil;
import com.cw.jeeyt.common.ResultData;
import com.cw.jeeyt.common.constants.ApiConstants;
import com.cw.jeeyt.common.enums.EnumOperateFlag;
import com.cw.jeeyt.common.web.BaseController;
import com.cw.jeeyt.service.bo.api.ApiFacadeDocBo;
import com.cw.jeeyt.service.intf.api.ApiFacadeDocService;
import com.cw.jeeyt.service.directive.PageDictDirective;
import com.cw.jeeyt.service.directive.PermissionDirective;
import com.cw.lang.common.utils.CollectionUtil;
import com.cw.lang.mybatis.dto.PageInfo;

/**
 * api接口文档控制层
 *
  * @author chenw
 * @version 1.0.0
 */
@Controller
@RequestMapping("/apiFacadeDoc")
public class ApiFacadeDocController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiFacadeDocController.class);
    @Resource
    private ApiFacadeDocService apiFacadeDocService;

    /**
     * 跳转到api接口文档列表查询页面
     *
     * @param apiFacadeDocBo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/query")
    public ModelAndView query() throws Exception {

        ModelAndView mv = new ModelAndView("api/apiFacadeDoc_index");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        return mv;
    }

    /**
     * 跳转到api接口文档列表查询页面
     *
     * @param apiFacadeDocBo
     * @return
     */
    @RequestMapping(value = "/query_select")
    public ModelAndView querySelectInfo(String selectType, String returnMethod) {

        ModelAndView mv = new ModelAndView("api/apiFacadeDoc_selectIndex");
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("selectType", selectType);
        mv.addObject("returnMethod", returnMethod);
        return mv;
    }

    /**
     * 加载DataTable列表数据
     *
     * @param dataTable 请求数据
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/listApiFacadeDoc")
    public ResultData listApiFacadeDoc(@RequestBody DataTable dataTable) throws Exception {

        ApiFacadeDocBo apiFacadeDocBo = JSONObject.parseObject(JSON.toJSONString(dataTable.getQueryCond()),
            ApiFacadeDocBo.class);
        if (apiFacadeDocBo == null) {
            apiFacadeDocBo = new ApiFacadeDocBo();
        }
        PageInfo<ApiFacadeDocBo> pageInfo = apiFacadeDocService.queryByPage(apiFacadeDocBo, dataTable.getStart(),
            dataTable.getLength(), dataTable.getOrder()[0]);
        return ResultData.builder()
            .draw(dataTable.getDraw())
            .data(CollectionUtil.isNotEmpty(pageInfo.getList())?pageInfo.getList():new ArrayList())
            .recordsTotal(pageInfo.getTotal())
            .recordsFiltered(pageInfo.getTotal())
            .build();
    }

    /**
     * 跳转到api接口文档表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-tab")
    public ModelAndView toEditTab(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiFacadeDoc_tab");
        ApiFacadeDocBo apiFacadeDocBo;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            apiFacadeDocBo = new ApiFacadeDocBo();
        } else {
            apiFacadeDocBo = apiFacadeDocService.getApiFacadeDocById(id);
        }
        mv.addObject("apiFacadeDoc", apiFacadeDocBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        mv.addObject("docId", id);
        return mv;
    }

    /**
     * 跳转到api接口文档表单页面
     *
     * @param operation 操作  add 新增 edit修改 view查看
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/to-form")
    public ModelAndView editForm(Long id, String operation) throws Exception {

        ModelAndView mv = new ModelAndView("api/apiFacadeDoc_form");
        ApiFacadeDocBo apiFacadeDocBo;
        if (EnumOperateFlag.ADD.getCode()
            .equals(operation)) {
            apiFacadeDocBo = new ApiFacadeDocBo();
        } else {
            apiFacadeDocBo = apiFacadeDocService.getApiFacadeDocById(id);
        }
        mv.addObject("apiFacadeDoc", apiFacadeDocBo);
        mv.addObject("operation", operation);
        mv.addObject("PageDict", new PageDictDirective());
        mv.addObject("permission", new PermissionDirective());
        return mv;
    }

    /**
     * 根据操作类型保存api接口文档数据
     *
     * @param apiFacadeDocBo
     * @param operation add 新增  edit 修改
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/saveApiFacadeDoc", method = RequestMethod.POST)
    public JsonResultDto saveApiFacadeDoc(ApiFacadeDocBo apiFacadeDocBo, String operation) {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            if (operation.equals(EnumOperateFlag.ADD.getCode())) {
                apiFacadeDocService.insert(apiFacadeDocBo);
            } else if (operation.equals(EnumOperateFlag.EDIT.getCode())) {
                apiFacadeDocService.update(apiFacadeDocBo);
            }
            jsonResultDto.setMsg("保存成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("保存失败:" + e.getMessage());

            e.printStackTrace();
            logger.error("保存api接口文档失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 删除api接口文档
     *
     * @param apiFacadeDocBo
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public JsonResultDto delete(ApiFacadeDocBo apiFacadeDocBo)
    throws Exception {

        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiFacadeDocService.delete(apiFacadeDocBo);
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();

            jsonResultDto.setMsg("删除失败：" + e.getMessage());
            logger.error("删除api接口文档失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 跳转到导入接口文档页面
     *
     * @return
     */
    @RequestMapping(value = "/to-importApiDocPage")
    public ModelAndView toImportExamQuestion() {
        ModelAndView mv = new ModelAndView("api/apiFacadeDoc_importForm");
        return mv;
    }

    /**
     * 导入题目
     *
     * @param request
     */
    @ResponseBody
    @RequestMapping(value = "/importApiFacadeDoc", method = RequestMethod.POST)
    public JsonResultDto importExamQuestion(HttpServletRequest request) {
        JsonResultDto jsonResultDto = new JsonResultDto(false);
        try {
            apiFacadeDocService.importApiFacadeDoc(request);
            jsonResultDto.setMsg("导入接口文档成功");
            jsonResultDto.setSuccess(true);
        } catch (Exception e) {
            jsonResultDto.setMsg("导入接口文档失败：" + e.getMessage());

            logger.error("导入接口文档失败：" + e.getMessage());
        }
        return jsonResultDto;
    }

    /**
     * 下载接口文档模板
     *
     */
    @RequestMapping(value = "/download_doc_template")
    public void downloadApiFacadeDocTemplate(HttpServletRequest request, HttpServletResponse response) {
        try {
            DownLoadTemplateUtil.downloadTemplate(request, response, ApiConstants.API_FACADE_DOC_TEMPLATE_FILE);
            logger.info("下载接口文档模板成功");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("下载接口文档模板失败：" + e.getMessage());
        }
    }
}
